package servlet;

import entity.User;
import service.UserService;
import service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

@WebServlet(name = "UserServlet",urlPatterns = "/UserServlet")
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String opr = request.getParameter("opr");
        HttpSession session = request.getSession();
        UserService userService = new UserServiceImpl();
        //Integer uid = ((User)session.getAttribute("user")).getId();
        if (opr.equals("user")){

            String userName = request.getParameter("ue") ;
            String password = request.getParameter("password") ;
            boolean isAutoLogin = false;
            User user = null;
            try {
                user = userService.login(userName,password);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            if (user==null){
                out.print("<script type='text/javascript'>");
                out.print("alert('登录账号与密码不匹配，请重新登录');");
                out.print("window.history.back(-1);");
                out.print("</script> ");
            }else {
                session.setAttribute("user", user);
                session.setMaxInactiveInterval(60 * 60);
                if (isAutoLogin) {
                    Cookie cookie1 = new Cookie("username", userName);
                    Cookie cookie2 = new Cookie("password", password);
                    cookie1.setMaxAge(60 * 60 * 24);
                    cookie2.setMaxAge(60 * 60 * 24);
                    response.addCookie(cookie1);
                    response.addCookie(cookie2);
                } else {
                    Cookie[] cookies = request.getCookies();
                    for (Cookie cookie : cookies) {
                        if (cookie.getName().equals("username")) {
                            cookie.setMaxAge(0);
                            response.addCookie(cookie);
                        }
                        if (cookie.getName().equals("password")) {
                            cookie.setMaxAge(0);
                            response.addCookie(cookie);
                        }
                    }
                }
                if (userName.equals("admin")){
                    request.getRequestDispatcher("admin/index.jsp").forward(request,response);
                }else {
                    request.getRequestDispatcher("/GoodsServlet?opr=goods1").forward(request,response);
                }

            }
        }else if (opr.equals("center")){

            request.getRequestDispatcher("user_center.jsp").forward(request,response);
        }else if (opr.equals("changeaddress")){
            String name = request.getParameter("name") ;
            String phone = request.getParameter("phone") ;
            String address = request.getParameter("address");
            if ((name==null||name.equals(""))&&(phone==null||phone.equals(""))&&(address==null&& address.equals(""))){
                out.print("<script type='text/javascript'>");
                out.print("    alert('收货信息不能为空');");
                out.print("    window.history.back(-1);");
                out.print("</script> ");
            }else {
                User user = new User();
                user.setId(((User)session.getAttribute("user")).getId());
                user.setName(name);
                user.setPhone(phone);
                user.setAddress(address);
                int result = userService.updateUser(user);
                if (result>0){
                    response.sendRedirect(request.getHeader("Referer"));//返回并刷新
                }else {
                    //添加失败。给出提示
                    out.println("<script type='text/javascript'>");
                    out.println("alert('修改失败！请重新修改');");
                    out.println("window.history.back(-1);");
                    out.println("</script>");
                }
            }
        }else if (opr.equals("changepwd")){
            String password = request.getParameter("newPassword") ;
            if (password==null||password.equals("")){
                out.print("<script type='text/javascript'>");
                out.print("alert('密码不能为空');");
                out.print("window.history.back(-1);");
                out.print("</script> ");
            }else {
                User user = new User();
                user.setId(((User) session.getAttribute("user")).getId());
                user.setPassword(password);
                int result = userService.updatePwd(user);
                if (result > 0) {
                    out.print("<script type='text/javascript'>");
                    out.print("alert('修改成功');");
                    out.print("window.history.back(-1);");
                    out.print("</script> ");
                    //response.sendRedirect(request.getHeader("Referer"));//返回并刷新
                } else {
                    //添加失败。给出提示
                    out.print("<script type='text/javascript'>");
                    out.print("alert('修改失败！请重新修改');");
                    out.print("window.history.back(-1);");
                    out.print("</script> ");
                }
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        doGet(req,resp);
    }
}
